$(function(){
  $("#reg").validate({
    rules:{
			Email:{required:true,email:true},
			username:{required:true,minlength:5,maxlength:20},
			password:{required:true,minlength:6,maxlength:16},
			password_again:{equalTo:"#password",required:true}
			},			 
    messages:{
			Email:{required:'邮箱不能为空!',email:'邮箱格式错误'},
			username:{required:'用户名不能为空',minlength:'用户名长度5~20位（1个中文算1位）',maxlength:'用户名长度5~20位（1个中文算1位）'},
			password:{required:'密码不能为空',minlength:'密码长度6~16位',maxlength:'密码长度6~16位'},
			password_again:{equalTo:'两次输入的密码不一致，请重新输入',required:'密码不能为空'}
			},
	errorElement:"em",
	success:function(label){label.text("").addClass("success")}		 
		 });
});

//用来检验用户名是否合法，是否含有非法字符，包括是否已被注册，用户每输入一个字符就要检验一次。
$(function(){
	$("#username").keyup( function(){

		var arg = new Object();
		arg.username=$("#username").val();

		//判断用户名是否含有非法字符
		var index = arg.username.length-1;
		var checkchar;

		var num_patrn =/^[0-9]+$/;
		var chinese_patrn=/^[\u4e00-\u9fa5]{0,}$/;
		var english_patrn=/[a-zA-Z]/;

		for( var i=0; i<=index; i++)
		{
			checkchar = arg.username.charAt(i);
			
			if( num_patrn.exec(checkchar) ) //是数字
			{
				continue;
			}
			else if( chinese_patrn.exec(checkchar) ) //是中文
			{
				continue;
			}
			else if( english_patrn.exec(checkchar) ) //是英文
			{
				continue;
			}
			else if( '_' == checkchar ) //是下划线
			{
				continue;
			}
			else
			{
				alert(checkchar+"是非法字符");
				if( ! $("#button").attr("disabled") )
				{	
					$("#button").attr("disabled","");
				}
				return;
			}
		}
		if( $("#button").attr("disabled") )
		{
			$("#button").removeAttr("disabled");
		}

		

		//判断用户名是否已被注册
		var x = call_serviceurl(22, arg, false); //false代表同步调用ajax, true代表异步

		if(true == x)
		{
			alert("很抱歉，此用户名已注册");
			$("#button").attr("disabled","");
		}
		else if(false == x )
		{
			if( $("#button").attr("disabled") )
			{
				$("#button").removeAttr("disabled");
			}
			//alert("未注册");
		}
		else
		{
			alert("未知错误");
		}

	});
});